import Vue from 'vue';
import { Loading, Message } from 'element-stm';

export default async function ajaxWithLoading(payload) {
  const params = Object.assign({}, {
    url: '',
    data: {},
    type: 'OPTIONS',
    success: null,
    error: null,
  }, payload);

  if (!params.url) {
    Message({
      message: 'AJAX方法缺少接口地址！',
    });
    return;
  }

  const loadingInstance = Loading.service({
    target: '.container',
    lock: true,
  });

  params.type = params.type.toUpperCase();
  if (params.type === 'POST') {
    await Vue.http.post(params.url, params.data).then(
      (res) => {
        if (typeof params.success === 'function') {
          params.success(res.body);
        }
      },
      (res) => {
        if (typeof params.error === 'function') {
          params.error(res.body);
        }
      },
    );
  } else if (params.type === 'GET') {
    await Vue.http.get(params.url, params.data).then(
      (res) => {
        if (typeof params.success === 'function') {
          params.success(res.body);
        }
      },
      (res) => {
        if (typeof params.error === 'function') {
          params.error(res.body);
        }
      },
    );
  }

  loadingInstance.close();
};
